package no21.thread;

import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
 * 从线程中产生返回值
 * 要
 * @author gao
 *
 */
class TaskWithResult implements Callable<String> {
	private int id;

	public TaskWithResult(int id) {
		this.id = id;
	}

	@Override
	public String call() {
		//让i==5时,执行的慢些,看结果可以看到 id=5的打不出来
		if(id==5){
			for (int i = 0; i < 10000000; i++) {
				new StringBuffer();
			}
		}
		//先执行业务逻辑
		//再表示任务的未决结果的 Future
		return "result of TaskWithResult " + id;
	}
}

public class CallableDemo {
	public static void main(String[] args) {
		ExecutorService exec = Executors.newCachedThreadPool();
		ArrayList<Future<String>> results = new ArrayList<Future<String>>();
		for (int i = 0; i < 10; i++) {
			//使用submit调用线程
			results.add(exec.submit(new TaskWithResult(i)));
		}
		
		for (Future<String> future:results) {
			try {
				// Future 先判断是否已完成,再get结果 也可以直接get(这样get是阻塞的)
				if(future.isDone()){
					System.out.println(future.get());
				}
				
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
